package com.one.shopping.ui.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.one.shopping.R;
import com.one.shopping.adapter.OrdersGoodsAdapter;
import com.one.shopping.api.OneApi;
import com.one.shopping.entity.Member;
import com.one.shopping.entity.Orders;
import com.one.shopping.entity.Result;
import com.one.shopping.entity.ShoppingCart;
import com.one.shopping.ui.baseActivity.BaseActivity;
import com.one.shopping.util.GsonUtils;

import org.apache.http.Header;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OrdersDetailActivity extends BaseActivity implements TextWatcher{

	private TextView ordersIdDataTv;
	private TextView dateDataTv;
	private TextView memberCardDataTv;
	private TextView userDataTv;
	private ListView tradeLv;
	private TextView numbersDataTv;
	private TextView needToPayDataTv;
	private TextView memberCardPayDataTv;
	private TextView balanceDataTv;
	private TextView fillMoneyDataTv;
	private TextView changeDataTv;
	private EditText payDataEt;
	private Button finishBtn;
	private RadioGroup modeOfPayRgp;
	private RadioButton cashRbtn;
	private RadioButton memberCardRbtn;
	private double totalMoney;
	private int userId;
	private String orderId;
	private int lucnNum;
	private int cardId;
	private float discount = 0.8f; // 折扣
	private int mode;
	private TextView memberCardPayTv;
	private TextView balanceTv;
	private TextView fillMoneyTv;
	private BaseAdapter adapter;
	private double memberScore;
	private List<ShoppingCart> shoppingCarts;
	private int sum;
	private String date;
	private Button cancelBtn;
	private boolean isPay;
	private TextView warningTv;
	private String payString;
	private DecimalFormat df;


	@Override
	protected int getContentViewId() {
		return R.layout.orders_detail_activity;
	}

	@Override
	protected void initView() {
		super.initView();
		setTitle("订单详情");

		ordersIdDataTv = (TextView) findViewById(R.id.ordersIdDataTv); // 订单编号
		dateDataTv = (TextView) findViewById(R.id.dateDataTv); // 日期
		memberCardDataTv = (TextView) findViewById(R.id.memberCardDataTv); // 会员卡号
		userDataTv = (TextView) findViewById(R.id.userDataTv); // 收银员工号
		tradeLv = (ListView) findViewById(R.id.tradeLv); // 商品列表
		numbersDataTv = (TextView) findViewById(R.id.numbersDataTv); // 商品数量
		needToPayDataTv = (TextView) findViewById(R.id.needToPayDataTv); // 应付总金额
		modeOfPayRgp = (RadioGroup) findViewById(R.id.modeOfPayRgp); // 付款方式
		cashRbtn = (RadioButton) findViewById(R.id.cashRbtn); // 现金支付按钮
		memberCardRbtn = (RadioButton) findViewById(R.id.memberCardRbtn); // 会员卡支付按钮
		memberCardPayTv = (TextView) findViewById(R.id.memberCardPayTv); // 会员卡支付标题
		memberCardPayDataTv = (TextView) findViewById(R.id.memberCardPayDataTv); // 会员卡支付金额
		balanceTv = (TextView) findViewById(R.id.balanceTv); // 会员卡余额标题
		balanceDataTv = (TextView) findViewById(R.id.balanceDataTv); // 会员卡余额
		fillMoneyTv = (TextView) findViewById(R.id.fillMoneyTv); // 差价补现标题
		fillMoneyDataTv = (TextView) findViewById(R.id.fillMoneyDataTv); // 差价补现
		changeDataTv = (TextView) findViewById(R.id.changeDataTv); // 找零
		payDataEt = (EditText) findViewById(R.id.payDataEt); // 付款金额
		finishBtn = (Button) findViewById(R.id.finishBtn); // 完成支付
		cancelBtn = (Button) findViewById(R.id.cancelBtn); // 完成支付
		warningTv = (TextView) findViewById(R.id.warningTv);	//警示语

		/**
		 * 接收前一个页面发送过来的值
		 */
		Intent intent = getIntent();
		totalMoney = intent.getDoubleExtra("money", 0); // 总金额
		userId = intent.getIntExtra("userId", -1); // 员工号
		orderId = intent.getStringExtra("orderId"); // 订单号
		lucnNum = intent.getIntExtra("luckNum", 0); // 是否为幸运订单，1为是，0为否
		cardId = intent.getIntExtra("cardId", 0); // 会员卡号
		shoppingCarts = (List<ShoppingCart>) intent.getSerializableExtra("shoppingcartList");
		for (int i = 0; i < shoppingCarts.size(); i++) {
			sum = sum + shoppingCarts.get(i).getQuantity();
		}

		isPay = false; // 设置未支付状态

		df = new DecimalFormat(".##");
		adapter = new OrdersGoodsAdapter(OrdersDetailActivity.this, shoppingCarts); // 设置清单的适配器
		tradeLv.setAdapter(adapter);

		/**
		 * 为各个组件赋值
		 */
		numbersDataTv.setText(sum + ""); // 商品件数
		date = getDate(); // 日期
		ordersIdDataTv.setText(orderId + ""); // 订单编号
		dateDataTv.setText(date);
		if (cardId == 0) {
			memberCardDataTv.setText("无"); // 会员卡号
			memberCardRbtn.setVisibility(View.GONE);
		} else {
			memberCardDataTv.setText(cardId + "");
			memberCardRbtn.setVisibility(View.VISIBLE);
		}

		userDataTv.setText(userId + ""); // 员工号

		if (lucnNum == 0) {
			needToPayDataTv.setText(totalMoney + ""); // 总价格，如果是幸运订单，总结格将乘以折扣价

		} else {
			totalMoney = (int) (totalMoney * discount);
			needToPayDataTv.setText(totalMoney + "");

		}

//		getChange(); // 找零
		changeDataTv.setText("0");

		modeInit(); // 付款方式初始化

		/**
		 * 设置付款方式监听
		 */
		modeOfPayRgp.setOnCheckedChangeListener(new OnCheckedChangeListenerImp());

		/**
		 * 设置付款金额的监听事件，当完成输入立即得出找零的钱数
		 */
		payDataEt.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				getChange();
				return false;
			}
		});

		finishBtn.setOnClickListener(OnFinishBtnListener);
		cancelBtn.setOnClickListener(OnCancelBtnListener);
		payDataEt.addTextChangedListener(this);
	}

	/**
	 * 取消支付监听事件
	 */
	private OnClickListener OnCancelBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			    Builder builder = new Builder(OrdersDetailActivity.this);
		        builder.setMessage("确定要取消支付吗?");  
		        builder.setTitle("提示");  
		        builder.setPositiveButton("确认",  
		        new DialogInterface.OnClickListener() {
		            @Override  
		            public void onClick(DialogInterface dialog, int which) {  
		            	deleteOrder();
//		            	Intent aIntent = new Intent();
//		            	aIntent.setClass(OrdersDetailActivity.this, GoodsActivity.class);
//		            	startActivity(aIntent);
						finish();
		            }  
		        });  
		        builder.setNegativeButton("取消",  
		        new DialogInterface.OnClickListener() {
		            @Override  
		            public void onClick(DialogInterface dialog, int which) {  
		                dialog.dismiss();  
		            }  
		        });  
		        builder.create().show();  
			

		}

		/**
		 * 删除订单
		 */
		private void deleteOrder() {
			OneApi.deleteOrders(orderId, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					Result result = GsonUtils.fromJson(new String(arg2), Result.class);
					Log.d("info" ,result.getMessage());
//					Toast.makeText(getAc, result.getMessage() ,Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					Toast.makeText(OrdersDetailActivity.this, "网络错误！" ,Toast.LENGTH_SHORT).show();
				}
			});

		}
	};

	/**
	 * 完成支付监听事件
	 */
	private OnClickListener OnFinishBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {

			if (isPay) {
				updateMemberScore(); // 修改会员卡积分
				updateGoodsStock(); // 修改商品库存量
				addOrderDetail(); // 上传数据到订单详情表
				clearShoppingCart();//清空购物车
				warningTv.setText("");
				makeToast("支付成功！");
				Intent intent = new Intent();
				intent.setClass(OrdersDetailActivity.this, TabHostActivity.class);
				startActivity(intent);

				finish();

			} else {
				warningTv.setText("未支付或余额不足");
			}

		}
		/**
		 * 清空购物车
		 */
		public void clearShoppingCart(){
			SharedPreferences mySharedPreferences = getSharedPreferences("shoppingcart", Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = mySharedPreferences.edit();
			editor.clear();  
	        editor.commit();
		}

		/**
		 * 上传数据到订单详情表
		 */
		private void addOrderDetail() {
			for (int i = 0; i < shoppingCarts.size(); i++) {

				String goodsId = shoppingCarts.get(i).getId();
				int quantity = shoppingCarts.get(i).getQuantity();
				Orders orderDetail = new Orders(orderId, goodsId, quantity, totalMoney, date);
				OneApi.addOrdersDetail(orderDetail, new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						Result result = GsonUtils.fromJson(new String(arg2), Result.class);
//						Toast.makeText(OrdersDetailActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
						Log.d("info", result.getMessage());
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						Toast.makeText(OrdersDetailActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
					}
				});

			}
		}

		/**
		 * 修改商品库存量
		 */
		private void updateGoodsStock() {
			for (int i = 0; i < shoppingCarts.size(); i++) {

				String goodsId = shoppingCarts.get(i).getId();
				int quantity = shoppingCarts.get(i).getQuantity();

				OneApi.updateGoodsStock(goodsId, quantity, new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						Result result = GsonUtils.fromJson(new String(arg2), Result.class);
//						Toast.makeText(OrdersDetailActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
						Log.d("info", result.getMessage());
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						Toast.makeText(OrdersDetailActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
					}
				});
			}

		}

		/**
		 * 修改会员积分
		 */
		private void updateMemberScore() {
			if (cardId != 0) {
				OneApi.updateMemberScore(cardId, memberScore, new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						Result result = GsonUtils.fromJson(new String(arg2), Result.class);
						if (result.getCode() == 200)
							Toast.makeText(OrdersDetailActivity.this, "恭喜您获得了" + needToPayDataTv.getText()+ "积分", Toast.LENGTH_SHORT).show();
						else
							Toast.makeText(OrdersDetailActivity.this, "会员积分更新失败", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						Toast.makeText(OrdersDetailActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
					}
				});
			}
		}
	};

	/**
	 * 找零
	 */
	private void getChange() {
		String payString = payDataEt.getText().toString().trim();
		double pay = 0;
		double change = 0;
		double surplusMoney = 0;
		if (!payString.equals("")) {
			pay = Double.parseDouble(payString);
		}
		if (mode == 0) {
			surplusMoney = pay - Double.parseDouble(needToPayDataTv.getText().toString().trim());
			surplusMoney = changeNum(surplusMoney);
		} else {
			surplusMoney = pay - Double.parseDouble(fillMoneyDataTv.getText().toString().trim());
			surplusMoney = changeNum(surplusMoney);
		}

		if (surplusMoney < 0) {
			isPay = false;
			changeDataTv.setText("0");
		} else if (surplusMoney == 0) {
			isPay = true;
			changeDataTv.setText("0");
		} else {
			isPay = true;
			changeDataTv.setText(surplusMoney + "");
		}
	}

	/**
	 * 保留两位小数
	 */
	private double changeNum(double num){
		return Double.parseDouble(df.format(num));
	}


	/**
	 * 付款方式初始化
	 */
	private void modeInit() {
		mode = 0;
		memberCardPayDataTv.setVisibility(View.GONE);
		balanceDataTv.setVisibility(View.GONE);
		fillMoneyDataTv.setVisibility(View.GONE);
		memberCardPayTv.setVisibility(View.GONE);
		balanceTv.setVisibility(View.GONE);
		fillMoneyTv.setVisibility(View.GONE);
	}

	/**
	 * 获取日期
	 * 
	 * @return String
	 */
	private String getDate() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String date = formatter.format(curDate);
		return date;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		payString = payDataEt.getText().toString().trim();
		getChange();
	}

	/**
	 * 设置付款方式监听事件
	 */
	private class OnCheckedChangeListenerImp implements OnCheckedChangeListener {

		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (cashRbtn.getId() == checkedId) {
				modeInit();
			} else if (memberCardRbtn.getId() == checkedId) {
				mode = 1;
				memberCardPayDataTv.setVisibility(View.VISIBLE);
				balanceDataTv.setVisibility(View.VISIBLE);
				fillMoneyDataTv.setVisibility(View.VISIBLE);
				memberCardPayTv.setVisibility(View.VISIBLE);
				balanceTv.setVisibility(View.VISIBLE);
				fillMoneyTv.setVisibility(View.VISIBLE);

				OneApi.queryCardId(cardId, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {
						// TODO Auto-generated method stub
						Result result = GsonUtils.fromJson(new String(responseBody), Result.class);
						if (result.getCode() == 200) {
							Member member = GsonUtils.fromJson(result.getData(), Member.class);
							double memberMoney = Double.parseDouble(member.getMoney()); // 余额
							memberScore = Double.parseDouble(member.getScore()); // 积分
							double needPayCash = Double.parseDouble(needToPayDataTv.getText().toString().trim());
							if ((int) memberMoney - needPayCash > 0) {
								fillMoneyDataTv.setText("0");
							} else {
								fillMoneyDataTv.setText((int) needPayCash - memberMoney + "");
							}
							balanceDataTv.setText((int) memberMoney + "");
							memberCardPayDataTv.setText(needToPayDataTv.getText() + "");

							// 积分累加
							memberScore = memberScore + Double.parseDouble(needToPayDataTv.getText() .toString().trim());
						}

					}

					@Override
					public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
						// TODO Auto-generated method stub
						Toast.makeText(OrdersDetailActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
					}
				});
			}

		}
	}

}
